package top.anydata.lifeofcode.lifesystem.web.controller.admin.auth;

import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
import lombok.extern.slf4j.Slf4j;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;
import top.anydata.lifeofcode.lifesystem.dto.sys.user.SysAuthPermissionDto;
import top.anydata.lifeofcode.lifesystem.dto.sys.user.SysAuthRoleDto;
import top.anydata.lifeofcode.lifesystem.dto.sys.user.SysAuthUserDto;
import top.anydata.lifeofcode.lifesystem.service.common.ICommonService;
import top.anydata.lifeofcode.lifesystem.service.sys.user.IAuthRoleService;
import top.anydata.lifeofcode.lifesystem.service.sys.user.IAuthUserService;
import top.anydata.lifeofcode.lifesystem.web.requests.admin.SignUpRequest;
import top.anydata.lifeofcode.lifesystem.web.requests.admin.SigninRequest;
import top.anydata.lifeofcode.lifesystem.web.responses.admin.ApiResponse;
import top.anydata.lifeofcode.lifesystem.web.responses.admin.JwtAuthenticationResponse;

/**
 * 功能描述:
 *
 * @author <a href="mailto:caingao@anydata.top"/>
 * @version V1.0.0
 * @date 2023/9/5 13:58
 */
@Slf4j
@RestController
@RequestMapping("/sys/api/auth")
public class AuthenticationController {

    IAuthUserService authUserService;

    IAuthRoleService authRoleService;

    ICommonService commonService;

    AuthenticationController(IAuthUserService authUserService, ICommonService commonService, IAuthRoleService authRoleService) {
        this.authUserService = authUserService;
        this.commonService = commonService;
        this.authRoleService = authRoleService;
    }

    /**
     * 注册流程
     *
     * @param request
     * @return
     */
    @PostMapping("/signup")
    @SecurityRequirements
    public ResponseEntity<JwtAuthenticationResponse> signup(@RequestBody SignUpRequest request) {
        return ResponseEntity.ok(authUserService.signup(request));
    }

    /**
     * 登录流程
     *
     * @param request
     * @return
     */
    @PostMapping("/signin")
    @SecurityRequirements
    public ResponseEntity<ApiResponse<JwtAuthenticationResponse>> signin(@RequestBody(required = false) SigninRequest request) {
        if (!commonService.validateCaptcha(request.getCaptchaId(), request.getCaptcha())) {
            throw new BadCredentialsException("Invalid captcha");
        }
        return ResponseEntity.ok(ApiResponse.success(authUserService.signin(request)));
    }

    /**
     * 功能描述: 获取验证码.
     *
     * @author: <a href="mailto:caingao@anydata.top">CainGao</a>
     * @date: 3:54 PM 2024/2/6
     * @param: []
     * @return: org.springframework.http.ResponseEntity<java.util.Map < java.lang.String, java.lang.String>>
     */
    @GetMapping("/captcha")
    public ResponseEntity<ApiResponse<Map<String, String>>> getCaptcha() {
        Map<String, String> captchaData = commonService.generateCaptcha();
        return ResponseEntity.ok(ApiResponse.success(captchaData));
    }

    /**
     * 功能描述: 获取用户信息.
     *
     * @author: <a href="mailto:caingao@anydata.top">CainGao</a>
     * @date: 6:26 PM 2024/2/21
     * @param: [token]
     * @return: org.springframework.http.ResponseEntity<top.anydata.lifeofcode.lifesystem.web.responses.admin.ApiResponse < top.anydata.lifeofcode.lifesystem.dto.sys.user.SysAuthUserDto>>
     */
    @GetMapping("/userinfo")
    public ResponseEntity<ApiResponse<SysAuthUserDto>> getMe(@RequestHeader("Authorization") String token) {
        SysAuthUserDto sysAuthUserDto = authUserService.getUserInfoByToken(token);
        Set<SysAuthPermissionDto> rolePermissions = new HashSet<>();
        if (sysAuthUserDto != null) {
            for (SysAuthRoleDto sysAuthRoleDto : sysAuthUserDto.getRoles()) {
                int roleId = sysAuthRoleDto.getId();
                List<SysAuthPermissionDto> permissions = authRoleService.getPermissionsForRole(roleId);
                for(SysAuthPermissionDto permissionDto : permissions){
                    if( permissionDto.getType()==1) {
                        rolePermissions.add(permissionDto);
                    }
                }
            }
        }
        if (!rolePermissions.isEmpty()) {
            Map<String, List<SysAuthPermissionDto>> permissionMap = rolePermissions.stream()
                    .collect(Collectors.groupingBy(SysAuthPermissionDto::getParentId));
            for (SysAuthPermissionDto permission : rolePermissions) {
                String id = String.valueOf(permission.getId());
                if (permissionMap.containsKey(id)) {
                    permission.setChildren(permissionMap.get(id));
                }
                if (permission.getParentId() == null || permission.getParentId().equals("0")) {
                    sysAuthUserDto.getPermissions().add(permission);
                }
            }
        }
        log.debug("getMe:{}", JSON.toJSONString(sysAuthUserDto));
        return ResponseEntity.ok(ApiResponse.success(sysAuthUserDto));
    }

}
